package com.ht.right.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class CommonUtil {

	public static void toJsonStr(HttpServletResponse response, Object data) {
		if (data instanceof List || data instanceof Object[]|| data instanceof Set) {
			CommonUtil.toString(response, JSONArray.fromObject(data,getconfig()).toString());
			System.out.println(JSONArray.fromObject(data,getconfig()).toString());
		} else {
			CommonUtil.toString(response, JSONObject.fromObject(data,getconfig()).toString());
			System.out.println(JSONObject.fromObject(data,getconfig()).toString());
		}
	}
	
	public static JsonConfig getconfig(){
		 /*  //有级联，不能直接转化，要取出List放到map里面  
	    JsonConfig cfg = new JsonConfig();  
	    //过滤关联，避免死循环net.sf.json.JSONException: java.lang.reflect.InvocationTargetException  
	   cfg.setJsonPropertyFilter(new PropertyFilter()  
	    {   public boolean apply(Object source, String name, Object value) {  
	           if(name.contains("createDate") || name.contains("updateDate") || name.contains("expectStartDate")  || name.contains("expectEndDate") || name.contains("Time")) {  
	             return true;  
	           } else {  
	             return false;  
	          }  
	        }  
	       }); 
	    //net.sf.json.JSONException: java.lang.reflect.InvocationTargetException异常  
	   cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"});
	   */ 
	    //处理日期
	    JsonConfig cfg = new JsonConfig();  
	   cfg.registerJsonValueProcessor(java.util.Date.class,new JsonValueProcessor() {
           private final String format="yyyy-MM-dd";
           public Object processObjectValue(String key, Object value,JsonConfig arg2){
             if(value==null)
                   return "";
             if (value instanceof java.util.Date) {
                   String str = new SimpleDateFormat(format).format((java.util.Date) value);
                   return str;
             }
                   return value.toString();
           }
           public Object processArrayValue(Object value, JsonConfig arg1){
                      return null;
           }
        });
	   return cfg;  
	}
	
	
	
	public static void toString(HttpServletResponse response, Object data) {
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(data.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}

	}
	
	@SuppressWarnings("unchecked")
	public static List<Element> getXmlChildElements(String xml) {
		Document document=null;
		List<Element> childElements =null;
		try {
			document=DocumentHelper.parseText(xml); 
			//搜索文档中所有div中包含field属性的节点
			childElements = document.selectNodes("//div[@field]");
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return childElements;
	}
	
	// 判断对象是否为空
	public static boolean isNullOrEmpty(Object obj) {
		if (obj == null)
			return true;

		if (obj instanceof CharSequence)
			return ((CharSequence) obj).length() == 0;

		if (obj instanceof Collection)
			return ((Collection<?>) obj).isEmpty();

		if (obj instanceof Map)
			return ((Map<?, ?>) obj).isEmpty();

		if (obj instanceof Object[]) {
			Object[] object = (Object[]) obj;
			if (object.length == 0) {
				return true;
			}
			boolean empty = true;
			for (int i = 0; i < object.length; i++) {
				if (!isNullOrEmpty(object[i])) {
					empty = false;
					break;
				}
			}
			return empty;
		}
		return false;
	}
	// 把一个字符串的第一个字母大写  
    public static String upperFirstChar(String str) throws Exception{  
        byte[] items = str.getBytes();  
        items[0] = (byte) ((char) items[0] - 'a' + 'A');  
        return new String(items);  
    }  
    
    
    //转换成十位位日期格式
    public static String DateConversionString(Date date) {
	if (date == null) {
		return StringUtils.EMPTY;
	}
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	String str = sdf.format(date);
	return str;
}

/**
 * 将时间格式的数据转换成14位（yyyymmddHHmmss）
 * 
 * @param date
 *            Date类型
 * @return
 */
public static String DateConversion14String(Date date) {
	if (date == null) {
		return StringUtils.EMPTY;
	}
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
	String str = sdf.format(date);
	return str;
}
}


